﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Omu.Awesome.Mvc;
using Omu.AwesomeDemo.Core.Model;
using Omu.AwesomeDemo.Core.Repository;

namespace Omu.AwesomeDemo.WebUI.Controllers
{
    public class PersonLookupController : LookupController
    {
        private readonly IRepo<Person> repo;

        public PersonLookupController(IRepo<Person> repo)
        {
            this.repo = repo;
        }

        //overriding to put my custom search form which contains fname, lname, slCountry inputs
        public override ActionResult SearchForm()
        {
            return View();
        }

        public override ActionResult Header()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Search(IEnumerable<int> selected, string fname, string lname, int? slCountry, string show, int? page = null)
        {
            var result = repo.GetAll().Where(o =>
                                              o.FirstName.Containz(fname)
                                              && o.LastName.Containz(lname)
                                              && (o.Country.Id == slCountry || !slCountry.HasValue));
            
            if (selected != null) result = result.Where(o => !selected.Contains(o.Id));
            
            //show might come from AwesomeParameters attribute))
            if (show != null) result = result.Where(o => o.Show != null && o.Show.Name == show);

            //single select doesn't send page
            if (page == null)
                return View(@"awesome\LookupList", result);

            //multiselect
            const int pageSize = 7;
            var rows = this.RenderView(@"Awesome\LookupList", result.Skip((page.Value - 1) * pageSize).Take(pageSize));
            return Json(new { rows, more = result.Count() > page * pageSize });

        }

        public ActionResult Get(int id)
        {
            if (id == 0) return Content("");
            var person = repo.Get(id);
            return person == null ? Content("") : Content(person.FirstName + " " + person.LastName);
        }

        //for multiselect to show the already selected items in the popup
        public ActionResult Selected(IEnumerable<int> selected)
        {
            return View(@"Awesome\LookupList", repo.GetAll().Where(o => selected != null && selected.Contains(o.Id)));
        }

        //for multiselect to show to selected items in the control
        public ActionResult GetMultiple(IEnumerable<int> selected)
        {
            return Json(repo.GetAll().Where(o => selected.Contains(o.Id)).Select(v => new { Text = v.FirstName + ' ' + v.LastName }));
        }
    }
}